import editForm from "../form.vue";
import { message } from "@/utils/message";
// import { getUserList, updateUserInfo, deleteUser } from "@/api/user";

import {
  // getAllArticle,
  getAllcommentList,
  updateArticle,
  // deleteArticle,
  deletecomment
} from "@/api/community";

import { addDialog } from "@/components/ReDialog";
import { reactive, ref, onMounted, h } from "vue";
import { type FormItemProps } from "../utils/types";
import { type PaginationProps } from "@pureadmin/table";

export function useComment() {
  const form = reactive({
    username: ""
  });

  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });

  const formRef = ref();
  const dataList = ref([]);
  const loading = ref(true);
  // const { tagStyle } = usePublicHooks();

  const columns: TableColumnList = [
    {
      type: "selection",
      align: "left"
    },
    {
      label: "序号",
      type: "index",
      width: 70
    },
    {
      label: "作者ID",
      prop: "articleId",
      minWidth: 70
      // cellRenderer: scope => (
      //   <el-image
      //     style="width: 30px; height: 30px"
      //     src={scope.row.image_path}
      //     fit="fill"
      //     onClick={() => {
      //       window.open(scope.row.image_path, "_blank");
      //     }}
      //   />
      // )
    },
    {
      label: "评论内容",
      prop: "content"
      // align: "left"
    },
    {
      label: "二级评论ID",
      prop: "rootCommentId",
      minWidth: 70
    },
    {
      label: "给作者的ID",
      prop: "toUserId",
      minWidth: 70
    },

    {
      label: "用户ID",
      prop: "userId",
      minWidth: 70
    },

    {
      label: "状态",
      prop: "houseStatus",
      minWidth: 100,
      cellRenderer: ({ row, props }) => (
        // <el-tag size={props.size} style={tagStyle.value(row.status)}>
        <el-tag size={props.size}>{row.status}</el-tag>
      )
    },
    {
      label: "操作",
      fixed: "right",
      width: 160,
      slot: "operation"
    }
  ];

  function resetForm(formEl) {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  }

  async function onSearch() {
    loading.value = true;
    const { data } = await getAllcommentList({
      currentPage: pagination.currentPage,
      pageSize: pagination.pageSize
    }); // 这里是返回一维数组结构，前端自行处理成树结构，返回格式要求：唯一id加父节点parentId，parentId取父节点id
    console.log(data, "data");
    // if (!isAllEmpty(form.villageName)) {
    //   // 前端搜索部门名称
    //   newData = newData.filter(item => item.name.includes(form.villageName));
    // }
    // if (!isAllEmpty(form.houseStatus)) {
    //   // 前端搜索状态
    //   newData = newData.filter(item => item.houseStatus === form.houseStatus);
    // }
    // dataList.value = handleTree(newData); // 处理成树结构
    dataList.value = data?.records;
    pagination.total = data?.total;
    setTimeout(() => {
      loading.value = false;
    }, 500);
  }

  function openDialog(title = "新增", row?: FormItemProps) {
    addDialog({
      title: `${title}资产`,
      props: {
        formInline: {
          id: row?.id ?? null,
          articleId: row?.articleId ?? "",
          content: row?.content ?? "",
          rootCommentId: row?.rootCommentId ?? "",
          toUserId: row?.toUserId ?? "",
          userId: row?.userId ?? 0
          // houseStatus: row?.relationshipWithOwner ?? ""
        }
      },
      width: "40%",
      draggable: true,
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        // const pathUrl = formRef.value.pathUrl;
        const curData = options.props.formInline as FormItemProps;
        function chores() {
          message(`您${title}了资产拥有人为${curData.articleId}的这条数据`, {
            type: "success"
          });
          done(); // 关闭弹框
          onSearch(); // 刷新表格数据
        }
        FormRef.validate(async valid => {
          if (valid) {
            console.log("curData", curData);
            // 表单规则校验通过
            if (title === "新增") {
              // console.log(curData, "--");
              // 实际开发先调用新增接口，再进行下面操作
              // const res = await createHouse(curData);
              // console.log(res);
              chores();
            } else {
              // curData.imageUrl = pathUrl;
              // 实际开发先调用编辑接口，再进行下面操作
              const res = await updateArticle(curData);

              if (res.code === 200) {
                if (res.data.status == 201) {
                  message(`更新失败`, {
                    type: "error"
                  });
                } else {
                  chores();
                }
              }
            }
          }
        });
      }
    });
  }

  async function handleDelete(row) {
    console.log(row.id);
    const { data } = await deletecomment({ house_ids: [row.id] });
    console.log(data);
    message(`您删除了部门名称为${row.name}的这条数据`, { type: "success" });
    onSearch();
  }

  function handleSizeChange(val: number) {
    pagination.pageSize = val;
    onSearch();
  }

  function handleCurrentChange(val: number) {
    pagination.currentPage = val;
    onSearch();
  }

  const fileList = ref([]);
  const dialogVisible = ref(false);
  const tableData = ref([]);

  const isSelect = ref(false);
  const selectList = ref([]);

  function handleSelectionChange(val: any) {
    isSelect.value = val.length > 0;
    selectList.value = val;
  }

  async function batchHandle() {
    if (isSelect.value) {
      const ids = selectList.value.map((item: any) => item.id);
      const res = await deletecomment({ id: [...ids] });

      if (res.code == 200) {
        onSearch();
        message(`操作成功`, {
          type: "success"
        });
      }
    }
  }

  onMounted(() => {
    onSearch();
  });

  return {
    form,
    loading,
    columns,
    dataList,
    pagination,
    fileList,
    isSelect,
    dialogVisible,
    tableData,
    batchHandle,
    /** 搜索 */
    onSearch,
    /** 重置 */
    resetForm,
    /** 新增、编辑部门 */
    openDialog,
    /** 删除部门 */
    handleDelete,
    handleSelectionChange,
    handleSizeChange,
    handleCurrentChange
  };
}
